var laytpl, form, repeat_flag = false;
var temp_list = {};
var scanCode = {lastTime: 0, code: ''};

function clearBarCode() {
	scanCode = {lastTime: 0, code: ''}
}

// 监听扫码枪事件
$(window).keypress(function (e) {
	if (!checkStore()) {
		return false;
	}
	var currCode = e.keyCode || e.which || e.charCode;

	var currTime = new Date().getTime();
	if (scanCode.lastTime > 0) {
		if (currTime - scanCode.lastTime <= 100) {
			scanCode.code += String.fromCharCode(currCode);
		} else if (currTime - scanCode.lastTime > 500) {
			// 输入间隔500毫秒清空
			clearBarCode();
		}
	} else {
		scanCode.code = String.fromCharCode(currCode);
	}
	scanCode.lastTime = currTime;

	if (currCode == 13) {
		if (scanCode.code.trim().length > 0) {
			autocomplete(scanCode.code.trim(), function () {
				$(".stock-autocomplete-list").hide();
				$('.stock-autocomplete-list ul li:eq(0)').click();
			});
		} else if (!$(".stock-autocomplete-list").is(':hidden')) {
			$('.stock-autocomplete-list ul li:eq(0)').click();
		}
	}
});

layui.use(['form', 'laytpl'], function () {
	form = layui.form, laytpl = layui.laytpl;
	form.render();
	fetch({});

	//门店选择
	form.on('select(store_list)', function (data) {
		var store_id = data.value;
		if (default_store_id > 0) {
			layer.confirm('更改门店，将清除已录入的单报明细，确定吗?\n', {
				title: '操作提示',
				btn: ['是', '否'],
				closeBtn: 0,
				yes: function () {
					default_store_id = store_id;
					reset();
					layer.closeAll()
				},
				btn2: function () {

				}
			});
		} else {
			default_store_id = store_id;
		}

	});

	form.render('select');

	form.on('submit(save)', function (data) {

		if (Object.keys(stockData).length === 0) {
			layer.msg('请选择产品');
			return;
		}

		var check_return = false;
		var temp_data = Object.values(stockData);
		for (var i = 0; i < temp_data.length; i++) {
			if (temp_data[i].goods_num <= 0) {
				check_return = true;
				layer.msg('产品:' + temp_data[i].sku_name + '数量不能为空');
				break;
			}
		}

		if (check_return) return;

		if (stockConfig.is_audit == 1) {
			var temp_index = layer.confirm('单据保存后将处于"待审核"状态，只有经办人可以编辑或删除等操作！是否确认保存？', {
				title: '操作提示',
				btn: ['确定', '取消'],
				yes: function () {
					layer.close(temp_index);
					save();
				}
			});
		} else {
			save();
		}
	});

});

function back() {
	location.href = ns.url("stock://shop/stock/" + stockAction.listRoute)
}

function autocomplete(text, callback) {
	//根据写入的数据来查询相似的数据
	$.ajax({
		url: ns.url("stock://shop/stock/getskulist"),
		data: {search: text, store_id: defaultStoreId},
		dataType: 'JSON',
		type: 'POST',
		success: function (res) {
			$('.stock-autocomplete-list ul').html('');
			temp_list = {};
			if (res.data.length > 0) {
				$(".stock-autocomplete-list").show();
			} else {
				$(".stock-autocomplete-list").hide();
			}

			$.each(res.data, function (index, value) {
				temp_list[value.sku_id] = value;
				$('.stock-autocomplete-list ul').append('<li data-sku_id = "' + value.sku_id + '">' + value.sku_name + '</li>');
			});

			$('.stock-autocomplete-list ul li').hover(function () {
				$(".stock-autocomplete-list ul li").removeClass('stock-li-hover');
				$(this).addClass('stock-li-hover');
			}).click(function () {
				var sku_id = $(this).data('sku_id');
				var item = temp_list[sku_id];
				$(".stock-autocomplete-list").hide();
				$('.stock-search').val('');
				var temp_item = {};

				var temp_one_item = stockData[sku_id];
				if (ns.checkIsNotNull(temp_one_item)) {
					stockData[sku_id]['goods_num'] += 1;
				} else {
					item.goods_num = 0;
					item.goods_price = 0;
					item.goods_sku_id = sku_id;
					temp_item[sku_id] = item;
				}
				fetch(temp_item);
			});

			if (callback) callback();

		}
	});

}

$(function () {
	$(".stock-search").click(function (event) {
		if (!checkStore()) {
			return false;
		}
		if (!Object.keys(temp_list).length) autocomplete($(this).val());

		if (ns.checkIsNotNull(temp_list)) {
			$(".stock-autocomplete-list").show();
		}
		event.stopPropagation();
		return false;
	});

	var timeout = null;
	$("body").on('keyup', '.stock-search', function (e) {
		if (e.keyCode != 13) {
			var val = $(this).val();
			if (timeout) clearTimeout(timeout);
			timeout = setTimeout(function () {
				autocomplete(val);
			}, 800)
		}
	});

	$('body').click(function () {
		$(".stock-autocomplete-list").hide();
	})

});

//数据渲染（任何来源）
function fetch(data) {
	stockData = $.extend(stockData, data);
	//重新渲染
	var template = $("#stock_goods_info").html();
	$('.stock-body tr').not('.stock-search-line').remove();

	if (ns.checkIsNotNull(stockData)) {
		$.each(stockData, function (index, value) {
			laytpl(template).render(value, function (html) {
				$('.stock-body').append(html);
				form.render();
			})
		})
	} else {
		$('.stock-body').append('<tr> <td colspan="7" class="empty-data">无数据</td> </tr>');
	}
	form.render();
	syncData();
}

function dataChange(obj) {
	syncData();
}

function syncData() {
	var count_num = 0, goods_money = 0;
	var kinds_data = [];
	$('.stock-tr').each(function () {
		var obj = $(this);
		var key = obj.data('key');
		var goods_sku_id = obj.find('input[name=goods_sku_id]').val() || 0;
		var goods_num = parseFloat(obj.find('input[name=goods_num]').val()) || 0;
		var goods_price = parseFloat(obj.find('input[name=goods_price]').val()) || 0;
		if (kinds_data.indexOf(goods_sku_id) == -1) {
			kinds_data.push(goods_sku_id)
		}
		//重新采集数据
		stockData[key].goods_num = goods_num;//库存数量
		stockData[key].goods_price = goods_price;//库存价格
		count_num += goods_num;
		goods_money += goods_num * goods_price;
		obj.find('.total-cost-money').text(parseFloat(goods_num * goods_price).toFixed(2));
	});
	$(".kinds-num").text(parseInt(kinds_data.length));
	$(".count-num").text(parseFloat(count_num));
	$(".goods-money").text(parseFloat(goods_money).toFixed(2));
}

function reset() {
	stockData = {};
	temp_list = {};
	fetch();
	syncData();
}

function checkStore() {
	if (defaultStoreId == 0) {
		layer.msg('请先选择门店');
		return false;
	}
	return true;
}

function delTr(obj) {
	var parent = $(obj).parents('.stock-tr');
	var key = parent.data('key');//唯一值  (sku_id不承担)
	parent.remove();
	delete stockData[key];
	syncData();
}

function save() {
	if (repeat_flag) return false;
	repeat_flag = true;

	var data = {
		stock_json: JSON.stringify(stockData),
		store_id: defaultStoreId,
	};
	data[stockAction.id] = $('input[name="' + stockAction.id + '"]').val() || 0;

	$.ajax({
		type: 'post',
		dataType: 'JSON',
		url: ns.url("stock://shop/stock/" + stockAction.saveRoute),
		async: true,
		data: data,
		success: function (res) {
			if (res.code >= 0) {
				layer.confirm($('input[name="' + stockAction.id + '"]').val() ? '编辑成功' : '添加成功', {
					title: '操作提示',
					btn: ['返回列表', $('input[name="' + stockAction.id + '"]').val() ? '继续编辑' : '继续添加'],
					closeBtn: 0,
					yes: function () {
						location.href = ns.url("stock://shop/stock/" + stockAction.listRoute);
					},
					btn2: function () {
						repeat_flag = false;
						if ($('input[name="' + stockAction.id + '"]').val()) window.location.reload();
						else location.href = ns.url("stock://shop/stock/" + stockAction.saveRoute);
					}
				});
			} else {
				repeat_flag = false;
				layer.msg(res.message);
			}
			return false
		}
	})
}